package com.dcy.znoa.service.publiz.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dcy.znoa.common.enums.PushBusinessCode;
import com.dcy.znoa.common.util.Dysms;
import com.dcy.znoa.common.util.JpushUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.controller.publiz.model.SelectBaseModel;
import com.dcy.znoa.controller.publiz.model.messNotice.*;
import com.dcy.znoa.controller.sys.model.storeFile.AddStoreFileModel;
import com.dcy.znoa.dao.publiz.MessNoticeDao;
import com.dcy.znoa.dao.publiz.MessageDao;
import com.dcy.znoa.dao.sys.StoreFileDao;
import com.dcy.znoa.dao.user.OperDao;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.publiz.MessNotice;
import com.dcy.znoa.domain.publiz.Message;
import com.dcy.znoa.domain.sys.StoreFile;
import com.dcy.znoa.service.publiz.MessNoticeService;
import com.dcy.znoa.service.sys.StoreFileService;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Slf4j
@Service
public class MessNoticeServiceImpl implements MessNoticeService {

    @Autowired
    MessNoticeDao messNoticeDao;

    @Autowired
    MessageDao messageDao;

    @Autowired
    OperDao operDao;

    @Autowired
    StoreFileService storeFileService;

    @Autowired
    StoreFileDao storeFileDao;

    //查询公告
    @Override
    public Page<MessNotice> selectList(SelectMessNoticeModel model) throws InvocationTargetException, IllegalAccessException {
//        List<MessNotice> list = messNoticeDao.selectListMapper(model);
        EntityWrapper<MessNotice> ew = new EntityWrapper<>();
        MessNotice cp = new MessNotice();
        BeanUtils.copyProperties(cp, model);
        ew.setEntity(cp);
//        ew.eq("mess_id", model.getMessId())
//                .eq("receive_time", model.getReceiveTime())
//                .eq("receive_oper_id", model.getReceiveOperId())
//                .eq("valid_flag", model.getValidFlag());
        Integer total = SelectBaseModel.PageFill(model, ew, messNoticeDao);//加入分页参数
//        List<MessNotice> list = messNoticeDao.selectListMapper(ew);
//        return new JsonForList(list);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        page.setOrderByField("m.create_time");
        page.setAsc(false);
        List<MessNotice> list = messNoticeDao.selectListMapper(model, page);
        page.setRecords(list);
        return page;
    }

    //查询用户未读公告
    @Override
    public Page<MessNotice> selectUnReadList(SelectByReceiveOperIdModel model) {
//        List<MessNotice> list = messNoticeDao.selectListMapper(model);
        EntityWrapper<MessNotice> ew = new EntityWrapper<>();
        ew.isNull("receive_time")
                .eq("receive_oper_id", model.getReceiveOperId())
                .eq("valid_flag", 1)
                .orderBy("notice_id", false);//倒序
        Integer total = SelectBaseModel.PageFill(model, ew, messNoticeDao);//加入分页参数
//        List<MessNotice> list = messNoticeDao.selectListMapper(ew);
//        return new JsonForList(list);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<MessNotice> list = messNoticeDao.selectUnReadListMapper(model, page);
        page.setRecords(list);
        return page;
    }

    //查询用户已读公告
    @Override
    public Page<MessNotice> selectReadList(SelectByReceiveOperIdModel model) {
//        List<MessNotice> list = messNoticeDao.selectListMapper(model);
        EntityWrapper<MessNotice> ew = new EntityWrapper<>();
        ew.isNotNull("receive_time")
                .eq("receive_oper_id", model.getReceiveOperId())
                .eq("valid_flag", 1)
                .orderBy("notice_id", false);//倒序
        Integer total = SelectBaseModel.PageFill(model, ew, messNoticeDao);//加入分页参数
//        List<MessNotice> list = messNoticeDao.selectListMapper(ew);
//        return new JsonForList(list);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<MessNotice> list = messNoticeDao.selectReadListMapper(model, page);
        page.setRecords(list);
        return page;
    }

    @Transactional
    @Override
    public void insertBatch(AddMessNoticeListModel model) throws ClientException {
//        List<Integer> list = new ArrayList<Integer>();
//        Iterable<String> iter = Splitter.on(',').trimResults().omitEmptyStrings().split(model.getOperIdsStr());
//        iter.forEach(idStr -> {
//            MessNotice messNotice = new MessNotice(null,model.getMessId(),null,null,null,Long.valueOf(idStr),1,null,null,null);
//            messNoticeDao.insert(messNotice);
//                }
//        );
        StringBuilder sb = new StringBuilder("");
        String operIdsStr = model.getOperIdsStr();
        String[] ids = operIdsStr.split(",");
        int[] idInt = new int[ids.length];
        for (int i = 0; i < ids.length; i++) {
            idInt[i] = Integer.valueOf(ids[i]);
        }
        model.setIds(idInt);
        List<Oper> operList = operDao.selectOperListBatchIds(model);
        Date now = new Date();
        Integer messType = model.getMessType();
//        if (messType != null) {
//            switch (messType) {
//                case 3://说明是审核
//                    MessNotice messNoticeOwn = new MessNotice(null, model.getMessId(), null, null, null, model.getCreateOperId(), 1, null, null, now);
//                    messNoticeDao.insert(messNoticeOwn);
//                    break;
//                default:
//                    break;
//            }
        operList.forEach(oper -> {
            MessNotice messNotice = new MessNotice(model.getMessId(), oper.getOperId(), 1, now);
            messNoticeDao.insert(messNotice);
            Message message = messageDao.selectById(messNotice.getMessId());
            Map<String, String> pushMap = new HashMap<>();
//            pushMap.put("messId", message.getMessId().toString());
//            pushMap.put("title", message.getMessTitle());
//            pushMap.put("txt", message.getMessage());
            pushMap.put(PushBusinessCode.ACTION, PushBusinessCode.NOTICE.getCode());
            pushMap.put(PushBusinessCode.DATA, JSON.toJSONString(message));
            if (StringUtils.isNotBlank(oper.getPushId())) {
                JpushUtils.pushMsgByRegId(oper.getPushId(), pushMap);
//                JpushUtils.pushMsgByRegId(oper.getPushId(),PushBusinessCode.NOTICE.getMsg(),pushMap);
            }
            sb.append(oper.getPhoneNo() + ",");
//            if(message.getIsSms()!=null && message.getIsSms() > 0){
//                try {
//                    SendSmsResponse response = Dysms.sendSms(Dysms.MSG_CODE,oper.getPhoneNo(),message.getMessTitle());
//                    log.info("phoneNo=" + oper.getPhoneNo() + "messTitle ="+ message.getMessTitle());
//                    QuerySendDetailsResponse querySendDetailsResponse = Dysms.querySendDetails(response.getBizId(),oper.getPhoneNo());
//                    log.info("Code=" + querySendDetailsResponse.getCode());
//                    log.info("Message=" + querySendDetailsResponse.getMessage());
////                    System.out.println("短信明细查询接口返回数据----------------");
////                    System.out.println("Code=" + querySendDetailsResponse.getCode());
////                    System.out.println("Message=" + querySendDetailsResponse.getMessage());
////                    int i = 0;
////                    for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) {
////                        System.out.println("SmsSendDetailDTO[" + i + "]:");
////                        System.out.println("Content=" + smsSendDetailDTO.getContent());
////                        System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
////                        System.out.println("OutId=" + smsSendDetailDTO.getOutId());
////                        System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
////                        System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
////                        System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
////                        System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
////                        System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
////                    }
//                } catch (ClientException e) {
//                    e.printStackTrace();
////                    throw new BusinessException("404", "手机号码不存在!");
//                }
//            }
        });
        //发短信 通过用户id列表查询手机号码列表
        Integer isSms = model.getIsSms();
        if (isSms != null && isSms == 1) {
            sb.deleteCharAt(sb.length() - 1);
            Dysms.sendSms(Dysms.MSG_CODE, sb.toString(), model.getMessage());
        }
    }

    //暂时不用
    @Override
    public void updateBatch(UpdateMessNoticeListModel model) {
        List<Integer> list = new ArrayList<Integer>();
        Iterable<String> iter = Splitter.on(',').trimResults().omitEmptyStrings().split(model.getOperIdsStr());
        iter.forEach(idStr -> {
                    MessNotice messNotice = messNoticeDao.selectOne(new MessNotice(model.getMessId(), Long.valueOf(idStr), 1, new Date()));
                    messNoticeDao.update(new MessNotice(),
                            new EntityWrapper<MessNotice>().eq("mess_id", model.getMessId())
                                    .eq("receive_oper_id", Long.valueOf(idStr)));
                }
        );
    }

    @Transactional
    @Override
    public Long insertBatchAndMsg(AddMessNoticeListAndMsgModel model) throws
            InvocationTargetException, IllegalAccessException, BusinessException, ClientException {
        Message message = new Message();
        BeanUtils.copyProperties(message, model);
        if(model.getMessType()==null){
            model.setMessType(6);//公告
        }
        if(model.getMessType()==6){ //公告的时候，这里是消息表自己的 id ,所以不设置
            message.setEntityTbl(StoreFile.ENTITY_MSG);//公告的时候，这里是消息表自己的messsage
            message.setEntityId(null);
        }
//        message.setEntityTbl(model.getEntityTbl());//公告的时候，这里是消息表自己的messsage
        Message queryMsg = new Message();
        log.info(model.toString());
        log.info(message.toString());
        queryMsg.setEntityId(message.getEntityId());
        queryMsg.setEntityTbl(message.getEntityTbl());
        Message messageExist = null;
        if(message.getEntityId()!=null){
            messageExist = messageDao.selectOne(queryMsg);
        }
        if(messageExist==null){
            Integer resultAdd = messageDao.insert(message);
            if(resultAdd<=0){
                throw new BusinessException("404", "新增消息（公告）失败");
            }
        }else{
            message =  messageExist ;
        }
//        log.info("before begin update message");
        if(model.getMessType() == 6){
//            log.info("begin update message");
            message.setEntityId(message.getMessId());//公告的时候，这里是消息表自己的 id
            messageDao.updateById(message);//Integer result =
//            log.info("end update message result:"+ result);
        }
        Long messId = message.getMessId();
//        log.info("end update message messId："+messId);
        AddMessNoticeListModel addMessNoticeListModel = new AddMessNoticeListModel();
        BeanUtils.copyProperties(addMessNoticeListModel, model);
        addMessNoticeListModel.setMessId(messId);

        insertBatch(addMessNoticeListModel);
        String entityTbl =message.getEntityTbl();
        Long entityId = message.getEntityId();
        log.info("entityTbl & entityId "+entityTbl+" "+entityId);
        if(StringUtils.isNotBlank(entityTbl)&&entityId!=null){
            log.info("begin for");
            AddStoreFileModel addStoreFileModel = new AddStoreFileModel();
            BeanUtils.copyProperties(addStoreFileModel, model);
            addStoreFileModel.setEntityTbl(entityTbl);
            addStoreFileModel.setEntityId(entityId);
            String remoteFileNames = model.getRemoteFileName();
            log.info("remoteFileNames:"+remoteFileNames);
            if (StringUtils.isNotBlank(remoteFileNames)) {
//                if (model.getRemoteFileName() != null && model.getFileName() != null) {
                storeFileDao.delete(new EntityWrapper<StoreFile>().eq("entity_tbl",entityTbl).eq("entity_id",entityId));
                String[] fileNames = remoteFileNames.split(",");
                for (String remoteFileName : fileNames) {
                    StoreFile storeFile = new StoreFile();
                    BeanUtils.copyProperties(storeFile, addStoreFileModel);
                    storeFile.setRemoteFileName(remoteFileName);
                    storeFile.setFileName(remoteFileName);//三个名字都一样
                    storeFile.setDownloadPath(remoteFileName);//三个名字都一样
                    storeFileService.insert(storeFile);
                }
            }
        }

        return messId;
    }

    @Override
    public Integer read(Long messId, Long operId) {
        MessNotice messNotice = messNoticeDao.selectOne(new MessNotice(messId, operId));
        if (messNotice != null) {
            messNotice.setReceiveTime(new Date());
            return messNoticeDao.updateById(messNotice);
        }
        return null;
    }

    @Override
    public void insert(MessNotice var1) throws BusinessException, ClientException {

        Message message = messageDao.selectById(var1.getMessId());

        Map<String, String> pushData = new HashMap<String, String>();
//        pushData.put("messId", message.getMessId().toString());
//        pushData.put("title", message.getMessTitle());
//        pushData.put("txt", message.getMessage());
        message.setReceiveOperId(var1.getReceiveOperId());

        Map<String, String> pushMap = new HashMap<String, String>();
        pushMap.put(PushBusinessCode.ACTION, PushBusinessCode.NOTICE.getCode());
        pushMap.put(PushBusinessCode.DATA, JSON.toJSONString(message));


        Oper oper = operDao.selectById(var1.getReceiveOperId());
        if (!Strings.isNullOrEmpty(oper.getPushId())) {
            JpushUtils.pushMsgByRegId(oper.getPushId(), pushMap);
        }
        if (message.getIsSms() != null && message.getIsSms() > 0) {
            Dysms.sendSms(Dysms.MSG_CODE, oper.getPhoneNo(), message.getMessTitle());
        }

        Integer result = messNoticeDao.insert(var1);
        if (result == null || result <= 0) {
            throw new BusinessException(JsonCommon.INSERT_ERROR_CODE, JsonCommon.INSERT_ERROR_MSG);
        }
    }

    @Override
    public void updateById(MessNotice var1) throws BusinessException {
        Integer result = messNoticeDao.updateById(var1);
        if (result == null || result <= 0) {
            throw new BusinessException(JsonCommon.UPDATE_ERROR_CODE, JsonCommon.UPDATE_ERROR_MSG);
        }
    }
}
